//
//  OAuhViewController.swift
//  xinlangweibo
//
//  Created by yangshuo on 15/11/27.
//  Copyright © 2015年 yangshuo. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuhViewController: UIViewController {
    //
    private lazy var webView = UIWebView()
    
    @objc func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充账号密码-web注入(以代码的方式向web页面添加内容)
    @objc func autoFill(){
    let js = "document.getElementById('userId').value = '1264449521@qq.com'; "+"document.getElementById('passwd').value = 's89457797';"
      webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func loadView() {
        view = webView
        //设置代理,通过代理监听方法,来解决授权及取消时弹出百度界面的问题
        webView.delegate = self
        title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
//在开发中,如果是纯代码开发,视图最好指定背景颜色,如果nil,有可能影响效率!
        self.view.backgroundColor = UIColor .orangeColor()
        webView.loadRequest(NSURLRequest(URL: NetWork.sharedNetWork.oauhURL))
        
    }

    
  

}
//遵守代理协议
extension OAuhViewController: UIWebViewDelegate{
    //return true加载,return false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果请求的request.url是百度(如果授权后跳转到百度界面),那么不加载
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        //如果点击了取消那么不加载百度界面,而使用代码实现呢,就使用
        guard let query = url.query where query.hasPrefix ("code=") else{
            self.close()
            //如果点击了取消按钮,不显示回调的百度界面false
            return false
        }
        print(url.query)
        //从授权码中截取code=后面的授权码
let code = query.substringFromIndex("code=".endIndex)
        //输出授权码,通过获取授权码,才可以获得令牌
        print("授权码是" + code)
        
        
       // let url = request.URL
//        //查询主机地址
//        print(url.host)
//        //查询字符串(?后面的zifuchuan )
//        print(url.query)
//Users/shuo/Downloads/yangshuo/ui进阶/新浪微博/05天-界面切换/代码/07-用户账号/Weibo10/Weibo10/Classes/Model/UserAccount.swift/        print(request)
        
        
        //加载accessToken,将授权码->viewmodel,viewmodel中加载aceess_token,通过token获取account的模型数据,然后将数据返还给控制器

        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if(isSuccessed == true){
                print("成功了")
                //将获取的头像与昵称的account数据返回
                print(UserAccountViewModel.sharedUserAccount.account)
              
        //销毁控制器dismissViewControllerAnimated,有延迟不是立即将控制器销毁
                self.dismissViewControllerAnimated(false){
                    //停止指示器
                    SVProgressHUD.dismiss()
                    
                                NSNotificationCenter.defaultCenter().postNotificationName(WBSwithchRootControllerNotification, object: "QAQ")
                }
                //注意通知中心是同步的,会先执行监听方法,当监听方法执行完毕,再执行后续代码!

                
            }else{
                SVProgressHUD.showInfoWithStatus("正在玩命加载中")

//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//             self.close()
//        })
                //使用全局函数
                delay(2.0, callFun: { () -> () in
                    self.close()
                })
            }
            
        }
//获取授权码的同时隐藏授权后回调的百度界面
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
}
